const API_BASE_URL = '/api';

// 添加考勤记录函数
function showAddAttendanceForm() {
    fetch('/api/employees')
        .then(response => response.json())
        .then(teachers => {
            // 创建模态框
            const modalHtml = `
                <div id="addAttendanceModal" class="modal">
                    <div class="modal-content">
                        <h2>添加考勤记录</h2>
                        <select id="teacherId" class="form-control" required>
                            <option value="">请选择教师</option>
                            ${teachers.map(t => `<option value="${t.id}">${t.name} - ${t.department}</option>`).join('')}
                        </select>
                        <input type="date" id="attendanceDate" class="form-control" value="${new Date().toISOString().split('T')[0]}" required>
                        <div class="time-group">
                            <label>上班时间：</label>
                            <input type="time" id="checkIn" class="form-control" value="08:00" required>
                        </div>
                        <div class="time-group">
                            <label>下班时间：</label>
                            <input type="time" id="checkOut" class="form-control" value="17:00" required>
                        </div>
                        <div class="form-buttons">
                            <button onclick="cancelAddAttendance()" class="btn-cancel">取消</button>
                            <button onclick="submitAddAttendance()" class="btn-submit">提交</button>
                        </div>
                    </div>
                </div>
                <div id="modalOverlay" class="overlay"></div>
            `;
            
            // 添加到页面
            document.body.insertAdjacentHTML('beforeend', modalHtml);
            
            // 显示模态框
            document.getElementById('addAttendanceModal').style.display = 'block';
            document.getElementById('modalOverlay').style.display = 'block';
        })
        .catch(error => {
            console.error('Error:', error);
            alert('获取教师列表失败');
        });
}

// 取消添加考勤记录
function cancelAddAttendance() {
    const modal = document.getElementById('addAttendanceModal');
    const overlay = document.getElementById('modalOverlay');
    if (modal) modal.remove();
    if (overlay) overlay.remove();
}

// 提交添加考勤记录
function submitAddAttendance() {
    const teacherId = document.getElementById('teacherId').value;
    const date = document.getElementById('attendanceDate').value;
    const checkIn = document.getElementById('checkIn').value;
    const checkOut = document.getElementById('checkOut').value;

    if (!teacherId || !date || !checkIn || !checkOut) {
        alert('请填写所有字段');
        return;
    }

    fetch('/api/attendance/add', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            employeeId: parseInt(teacherId),
            date: date,
            checkIn: checkIn,
            checkOut: checkOut
        })
    })
    .then(response => {
        if (response.ok) {
            cancelAddAttendance();
            fetchAttendance();
            alert('添加考勤记录成功');
        } else {
            throw new Error('添加考勤记录失败');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('添加考勤记录失败');
    });
}

// 获取考勤记录
function fetchAttendance() {
    const dateFilter = document.getElementById('dateFilter').value;
    const departmentFilter = document.getElementById('departmentFilter').value;
    
    let url = `${API_BASE_URL}/attendance`;
    if (dateFilter) {
        url = `${API_BASE_URL}/attendance/date/${dateFilter}`;
    }
    
    fetch(url)
        .then(response => response.json())
        .then(data => {
            // 根据部门筛选
            const filteredData = departmentFilter 
                ? data.filter(record => record.department === departmentFilter)
                : data;
                
            displayAttendance(filteredData);
            // 保持所有部门的选项
            if (!departmentFilter) {
                updateDepartmentFilter(data);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('获取考勤记录失败');
        });
}

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    const today = new Date().toISOString().split('T')[0];
    const dateFilter = document.getElementById('dateFilter');
    const departmentFilter = document.getElementById('departmentFilter');
    
    if (dateFilter) {
        dateFilter.value = today;
        dateFilter.addEventListener('change', fetchAttendance);
    }
    
    if (departmentFilter) {
        departmentFilter.addEventListener('change', () => {
            fetchAttendance();
        });
    }
    
    fetchAttendance();
});

// 显示考勤记录
function displayAttendance(records) {
    const tbody = document.getElementById('attendanceList');
    if (!tbody) return;
    
    tbody.innerHTML = '';
    
    if (!records || records.length === 0) {
        tbody.innerHTML = '<tr><td colspan="7" class="text-center">暂无考勤记录</td></tr>';
        return;
    }
    
    records.forEach(record => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${record.date}</td>
            <td>
                <img src="/images/avatar-default.png" class="employee-avatar" alt="Avatar">
                ${record.name || '未知'}
            </td>
            <td>
                <img src="${getDepartmentIcon(record.department)}" class="department-icon" alt="${record.department}">
                ${record.department || '未知'}
            </td>
            <td><i class="fas fa-sign-in-alt"></i> ${record.checkIn || '未知'}</td>
            <td><i class="fas fa-sign-out-alt"></i> ${record.checkOut || '未知'}</td>
            <td>${getStatusIcon(record.status)}</td>
            <td>
                <button onclick="editAttendance(${record.id})" class="btn-edit">
                    <i class="fas fa-edit"></i>
                </button>
                <button onclick="deleteAttendance(${record.id})" class="btn-delete">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        `;
        tbody.appendChild(row);
    });
}

// 获取状态图标
function getStatusIcon(status) {
    switch(status) {
        case '正常':
            return '<span class="status-badge normal"><i class="fas fa-check"></i> 正常</span>';
        case '迟到':
            return '<span class="status-badge late"><i class="fas fa-clock"></i> 迟到</span>';
        case '缺勤':
            return '<span class="status-badge absent"><i class="fas fa-times"></i> 缺勤</span>';
        default:
            return status;
    }
}

// 获取部门图标
function getDepartmentIcon(department) {
    const icons = {
        '建筑学院': 'images/department-icons/tech.png',
        '土木学院': 'images/department-icons/hr.png',
        '机械学院': 'images/department-icons/finance.png',
        '电气学院': 'images/department-icons/marketing.png',
        '计算机学院': 'images/department-icons/tech.png',
        '艺术学院': 'images/department-icons/hr.png',
        '管理学院': 'images/department-icons/finance.png'
    };
    return icons[department] || 'images/department-icons/default.png';
}

// 更新部门筛选下拉框
function updateDepartmentFilter(records) {
    const departments = new Set(records.map(record => record.department).filter(Boolean));
    const departmentFilter = document.getElementById('departmentFilter');
    if (!departmentFilter) return;
    
    departmentFilter.innerHTML = '<option value="">所有学院</option>';
    departments.forEach(dept => {
        if (dept) {
            departmentFilter.innerHTML += `<option value="${dept}">${dept}</option>`;
        }
    });
}

// 添加删除当天记录的函数
function deleteTodayAttendance() {
    if (!confirm('确定要删除今天的所有考勤记录吗？')) {
        return;
    }

    fetch('/api/attendance/today', {
        method: 'DELETE'
    })
    .then(response => {
        if (response.ok) {
            alert('删除今日考勤记录成功');
            fetchAttendance(); // 刷新列表
        } else {
            throw new Error('删除今日考勤记录失败');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('删除今日考勤记录失败');
    });
}

// 删除单条考勤记录
function deleteAttendance(id) {
    if (!confirm('确定要删除这条考勤记录吗？')) {
        return;
    }

    fetch(`/api/attendance/${id}`, {
        method: 'DELETE'
    })
    .then(response => {
        if (response.ok) {
            alert('删除考勤记录成功');
            fetchAttendance(); // 刷新列表
        } else {
            throw new Error('删除考勤记录失败');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('删除考勤记录失败');
    });
}